using System;
using System.Collections.Generic;
using UnityEngine;

namespace IcecreamView
{
    /// <summary>
    /// icecream页面管理器，是驱动所有页面的核心控制器，用于控制页面生成、展示、隐藏、跳转等操作
    /// </summary>
    public sealed class IC_Controller : IDisposable
    {

        public static IC_Controller InstantiateViewManager(IC_IViewConfig gameViewConfig, Transform parent)
        {
            return new IC_Controller(gameViewConfig, parent);
        }

        private IC_IViewConfig Config;

        private List<IC_AbstractView> ViewPool;

        public Transform UIparent;

        public IC_Controller(IC_IViewConfig gameViewConfig, Transform parent)
        {
            Init(gameViewConfig, parent);
        }

        private void Init(IC_IViewConfig gameViewConfig, Transform parent)
        {

            Config = gameViewConfig;

            Config.OnInit();

            UIparent = parent;

            ViewPool = new List<IC_AbstractView>();

            if (Config == null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(Config.GetDefaultViewTable()))
            {
                OpenView(Config.GetDefaultViewTable());
            }
        }

        /// <summary>
        /// 获取指定页面
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public T GetView<T>(string table) where T : IC_AbstractView
        {
            if (ContainsKeyView(table))
            {
                for (int i = 0; i < ViewPool.Count; i++)
                {
                    if (table.Equals(ViewPool[i].VIEWTABLE))
                    {
                        return (T)ViewPool[i];
                    }
                }
            }
            return default(T);
        }

        public T OpenView<T>(string table, bool isSinge = true , params IC_ViewData[] values) where T : IC_AbstractView
        {
            IC_AbstractView view = OpenView(table, isSinge , values);
            if (view != null)
            {
                return view as T;
            }
            return null;
        }

        public T OpenView<T>(bool isSinge = true , params IC_ViewData[] values) where T : IC_AbstractView
        {
            string cname = typeof(T).ToString();
            for (int i = 0; i < ViewPool.Count; i++)
            {
                if (ViewPool[i].GetType().Name.Equals(cname))
                {
                    return OpenView<T>(ViewPool[i].VIEWTABLE, isSinge , values);
                }
            }
            Debug.LogError("IC_Controller : 打开view失败，未找到指定T --- " + cname);
            return null;
        }

        /// <summary>
        /// 构建一个View对象
        /// </summary>
        /// <param name="Table">ViewTable</param>
        /// <returns></returns>
        private IC_AbstractView CreateView(string Table)
        {
            var viewModle = Config.GetViewModle(Table);
            IC_AbstractView gameViewAbstract = UnityEngine.Object.Instantiate(viewModle.GetView(), UIparent);
            gameViewAbstract.VIEWTABLE = Table;
            if (viewModle.IsOnce())
            {
                gameViewAbstract.isOnce = viewModle.IsOnce();
            }
            else
            {
                gameViewAbstract.isOnce = ContainsKeyView(Table);
            }
            gameViewAbstract.SetViewManager(this);
            gameViewAbstract.isOpen = false;
            gameViewAbstract.OnInitView();
            return gameViewAbstract;
        }
        
        /// <summary>
        /// 打开指定页面
        /// </summary>
        /// <param name="table"></param>
        /// <param name="isSinge"></param>
        /// <returns></returns>
        public IC_AbstractView OpenView(string table, bool isSinge = true , params IC_ViewData[] values)
        {
            int viewCount = getViewIndex(table, isSinge);
            if (viewCount != -1)
            {
                ViewPool[viewCount].isOpen = true;
                ViewPool[viewCount].gameObject.SetActive(true);
                ViewPool[viewCount].transform.SetAsLastSibling();
                ViewPool[viewCount].OnOpenView(values);
                return ViewPool[viewCount];
            }
            else if (Config.ContainsKey(table))
            {
                IC_AbstractView gameViewAbstract = CreateView(table);
                gameViewAbstract.isOpen = true;
                gameViewAbstract.gameObject.SetActive(true);
                gameViewAbstract.transform.SetAsLastSibling();
                gameViewAbstract.OnOpenView(values);
                ViewPool.Add(gameViewAbstract);
                return gameViewAbstract;
            }
            else
            {
                Debug.LogFormat("<color=yellow>{0}</color>" , "IC_Controller : 打开view失败，未找到指定table --- " + table);
                return null;
            }
        }

        /// <summary>
        /// 关闭所有页面 并打开指定页面
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public IC_AbstractView OpenViewAndCloseOther(string table , bool isSinge , params IC_ViewData[] values)
        {
            if (table == null)
            {
                return null;
            }
            for (int i = 0; i < ViewPool.Count; i++)
            {
                ViewPool[i].CloseView();
            }

            IC_AbstractView view = OpenView(table , isSinge , values);
            return view;
        }

        /// <summary>
        /// 打开指定的ViewModuleConnector页面
        /// </summary>
        /// <param name="table"></param>
        /// <param name="isSinge"></param>
        /// <returns></returns>
        public IC_ModuleConnector OpenConnectorView(string table, bool isSinge = true , params IC_ViewData[] values)
        {
            return OpenView<IC_ModuleConnector>(table, isSinge , values);
        }

        /// <summary>
        /// 判断指定table是否存在
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public bool ContainsKeyView(string table)
        {
            for (int i = 0; i < ViewPool.Count; i++)
            {
                if (table.Equals(ViewPool[i].VIEWTABLE))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 返回一个指定table的View对应下标
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public int getViewIndex(string table, bool isSinge = false, bool objectType = false)
        {
            for (int i = 0; i < ViewPool.Count; i++)
            {

                if (table.Equals(ViewPool[i].VIEWTABLE))
                {
                    if (isSinge)
                    {
                        return i;
                    }
                    else if (ViewPool[i].gameObject.activeSelf == objectType)
                    {
                        return i;
                    }
                }
            }
            return -1;
        }
       
        /// <summary>
        /// 关闭指定Table的页面
        /// </summary>
        /// <param name="table"></param>
        public void CloseView(string table)
        {
            if (ContainsKeyView(table))
            {
                var count = getViewIndex(table, false, true);
                if (count == -1) return;
                ViewPool[count].CloseView();
            }
        }

        /// <summary>
        /// 关闭指定Hash页面
        /// </summary>
        /// <param name="gameHash"></param>
        public void CloseViewForHash(int gameHash)
        {
            for (int i = 0; i < ViewPool.Count; i++)
            {
                if (ViewPool[i].gameObject.GetHashCode() == gameHash)
                {
                    ViewPool[i].CloseView();
                }
            }
        }

        /// <summary>
        /// 关闭指定类型的所有页面
        /// </summary>
        /// <param name="table"></param>
        public void CloseTableViews(string table)
        {
            if (table == null) return;
            for (int i = 0; i < ViewPool.Count; i++)
            {
                if (table.Equals(ViewPool[i].VIEWTABLE))
                {
                    ViewPool[i].CloseView();
                }
            }
        }

        /// <summary>
        /// 关闭所有页面
        /// </summary>
        public void CloseAllView()
        {
            for (int i = 0; i < ViewPool.Count; i++)
            {
                ViewPool[i].CloseView();
            }
        }

        /// <summary>
        /// 销毁指定的view
        /// </summary>
        /// <param name="hash"></param>
        public void DestoryViewAtHash(int hash)
        {
            for (int i = 0; i < ViewPool.Count; i++)
            {
                if (ViewPool[i].gameObject.GetHashCode() == hash)
                {
                    GameObject.Destroy(ViewPool[i].gameObject);
                    ViewPool.Remove(ViewPool[i]);
                    return;
                }
            }
        }

        [Obsolete("不在提供运行时修改View配置表", true)]
        public void SetConfig(IC_IViewConfig config)
        {
            Config = config;
        }

        public void Dispose()
        {
            if (Config != null) {
                Config.OnDispose();
            }
        }
    }
}
